package com.im.webws;

import com.alibaba.fastjson.JSON;
import com.im.domain.SocketMessage;
import com.im.domain.SocketUser;
import com.im.domain.User;
import com.im.domain.bean.TextMessage;
import com.im.domain.enumtype.MessageType;
import com.im.domain.enumtype.SendType;
import com.im.domain.enumtype.UserStatus;
import com.im.service.TextMessageService;
import com.im.util.IMManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by 岸芷汀翎 on 2017/1/26.
 * Description:
 */
@ServerEndpoint(value = "/im/{uid}")
@Lazy(value=true)
@Component
public class IMWebSocket {
	 @Autowired
    private TextMessageService tmService;
  

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {
    	if(tmService == null){
        	tmService = WebSocketConfig.appContext.getBean(TextMessageService.class);
        }
        User user = new User();
        user.setId(uid);
        user.setStatus(UserStatus.Online);
        //保存在线列表
        IMManager.addUser(user, session);
        print("当前在线用户：" + IMManager.getOnlineNum());
        print("缓存中的用户个数：" + IMManager.getCashNum());
        try {
			List<TextMessage> list = tmService.getList(uid, SendType.UNSENT, MessageType.FRIEND);
			if(list != null && list.size() > 0){
				list.stream().forEach(tm -> {
					try {
						session.getBasicRemote().sendText(JSON.toJSONString(tm));
						tm.setSendType(SendType.SENT);
						tmService.save(tm);
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        TextMessage tm = null;
        try {
            SocketMessage sm = JSON.parseObject(message, SocketMessage.class);
            //得到接收的对象
            User user = sm.getUser();
            tm = sm.getMessage();
            if(user != null && StringUtils.isNotEmpty(user.getId())){
            	IMManager.addUser(user, session);
            }
            if (tm == null || StringUtils.isEmpty(tm.getSendId())) {
                tm = null;
            } else {
                print("the tm:" + tm.toString());
                tm.setSendType(SendType.UNSENT);
                tm.setTimeStamp(new Date());
                if (MessageType.FRIEND == tm.getType()) {
                    SocketUser su = IMManager.getSocketUserByUserId(tm.getSendId());
                    if (su != null && su.getSession() != null && su.getSession().isOpen()) {
                        su.getSession().getBasicRemote().sendText(JSON.toJSONString(tm));
                        System.out.println("send message to "+tm.getSendName());
                        tm.setSendType(SendType.SENT);
                    }
                } else if (MessageType.GROUP == tm.getType()) {
                    List<String> ids = sm.getGroupIds();
                    if(ids != null && ids.size() > 0){
                    	for (String sendId : ids) {
                    		if(tm.getUserId().equals(sendId)){
                    			continue;
                    		}
                    		SocketUser su = IMManager.getSocketUserByUserId(sendId);
                    		if(su != null && su.getSession()!= null && su.getSession().isOpen()){
                    			try {
                                    su.getSession().getBasicRemote().sendText(JSON.toJSONString(tm));
                                } catch (IOException ie) {
                                    ie.printStackTrace();
                                }
                    		}
						}
                    }
                    tm.setSendType(SendType.SENT);
                }
            }
            if (tm != null && tmService != null) {
                tmService.save(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void error(Throwable t) {
        print("连接错误:" + t.getMessage());
        t.printStackTrace();
    }

    @OnClose
    public void close(Session session) {
        SocketUser su = IMManager.getSocketUserBySeesionId(session.getId());
        if (su != null) {
            su.getUser().setStatus(UserStatus.NotOnline);
            print(su.getUser().getName() + "用户掉线");
        }
        //print("当前在线用户："+LayIMFactory.createManager().getOnlineCount());

    }

    private void print(String message) {
        System.out.println(message);
    }
}
